package {
	
	import com.ggshily.game.model.ms3d.MS3DEvent;
	import com.ggshily.pv3d.model.ms3d.MS3D;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	
	import org.papervision3d.cameras.Camera3D;
	import org.papervision3d.core.proto.MaterialObject3D;
	import org.papervision3d.core.render.IRenderEngine;
	import org.papervision3d.materials.BitmapFileMaterial;
	import org.papervision3d.render.BasicRenderEngine;
	import org.papervision3d.scenes.Scene3D;
	import org.papervision3d.view.Viewport3D;

	[SWF(width=640, height=480, backgroundColor=0x808080, frameRate=30)]
	public class Ms3d extends Sprite
	{
		public static const MODELS : Array = [["turtle1.ms3d", "pturtle1.png"], ["test.ms3d", "skinr.JPG"]];
		
		private var _camera3D : Camera3D;
		private var _viewport3D : Viewport3D;
		private var _scene3D : Scene3D;
		private var _render : IRenderEngine;
		
		private var ms3d : MS3D;
		private var material : MaterialObject3D;
		
		public function Ms3d()
		{
			_camera3D = new Camera3D(30, 10, 500);
			
			_viewport3D = new Viewport3D();
			addChild(_viewport3D);
			
			_scene3D = new Scene3D();
			
			_render = new BasicRenderEngine();
			
			var modle : int = 1;
			
			material = new BitmapFileMaterial("./model/" + MODELS[modle][1], true);
			material.doubleSided = true;
			BitmapFileMaterial.callback = function() : void{
			
					ms3d = new MS3D("./model/" + MODELS[modle][0], material, 30);
					ms3d.addEventListener(MS3DEvent.LOAD_COMPLETE, onLoadComplete);
				};
			
		}

		private function onLoadComplete(e : Event) : void
		{
			ms3d.removeEventListener(MS3DEvent.LOAD_COMPLETE, onLoadComplete);
			
			var info : TextField = new TextField();
			info.multiline = true;
			info.autoSize = TextFieldAutoSize.LEFT;
			info.appendText("model:\"" + ms3d.name + "\"\n");
			info.appendText("vertices:" + ms3d.ms3d.arrVertices.length + "\n");
			info.appendText("triangles:" + ms3d.ms3d.arrTriangles.length + "\n");
			info.appendText("groups:" + ms3d.ms3d.arrGroups.length + "\n");
			info.appendText("joints:" + ms3d.ms3d.arrJoints.length + "\n");
			addChild(info);
			
//			_scene3D.addChild(new Sphere(new BitmapColorMaterial()));
			_scene3D.addChild(ms3d);
			ms3d.x = -200;
			ms3d.rotationY = 45;
//			_scene3D.addChild(new PaperPlane());
			addEventListener(Event.ENTER_FRAME, tickFrame);
		}

		private function tickFrame(e : Event) : void
		{
//			ms3d.rotationY += 1;
//			ms3d.play();
			_render.renderScene(_scene3D, _camera3D, _viewport3D);
		}

	}
}
